<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="工单ID" prop="id">
        <el-input
            v-model="queryParams.id"
            placeholder="请输入工单ID"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleEditSelected"
            :disabled="!selectedRow"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleDeleteSelected"
            :disabled="!selectedRow"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据列表 -->
    <el-table :data="dataList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="id" label="工单ID"></el-table-column>
      <el-table-column prop="createBy" label="创建者"></el-table-column>
      <el-table-column label="图片">
        <template v-slot:default="scope">
          <div v-for="(purl, index) in scope.row.imagePath ? [scope.row.imagePath] : []" :key="index">
            <img :src="getImageUrl(purl)"
                 alt="上传图片"
                 style="max-width: 100px; max-height: 100px;"
                 @error="handleImageError"
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="新建时间"></el-table-column>
      <el-table-column prop="updateTime" label="更改时间"></el-table-column>
      <el-table-column label="操作">
        <template v-slot:default="scope">
          <el-button size="mini" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="isEdit ? '修改工单' : '新增工单'" :visible.sync="dialogVisible" width="70%">
      <el-row :gutter="30">
        <el-col :span="10">
          <div class="form-section">
            <h3 class="section-title">裂纹修复</h3>
            <el-form :model="form" :rules="rules" ref="form" label-width="150px" class="main-form">
              <el-form-item label="叶片裂纹描述" prop="crackDescription">
                <el-input v-model="form.crackDescription"
                          placeholder="请输入内容"
                          type="textarea"
                          :rows="9"
                          class="input-field"
                ></el-input>
              </el-form-item>
              <!-- 增加间距 -->
              <div style="margin-bottom: 255px;"></div>
              <el-form-item label="上传图片">
                <el-upload
                    class="upload-demo"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-upload="beforeUpload"
                    :file-list="fileList"
                    list-type="picture"
                >
                  <el-button size="small" type="primary" class="upload-btn">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="form-section">
            <h3 class="section-title">参数设置</h3>
            <!--叶片修复参数设置-->
            <div class="sub-form-section">
              <h4 class="sub-section-title">叶片修复参数设置</h4>
              <el-form :model="form" :rules="bladeRepairRules" ref="bladeRepairForm" label-width="150px"
                       class="sub-form"
              >
                <el-form-item
                    v-for="(param, index) in form.bladeRepairParams"
                    :key="index"
                    :label="param.label"
                    :prop="`bladeRepairParams[${index}].value`"
                    class="sub-form-item"
                >
                  <el-input v-model="param.value"
                            placeholder="请输入内容"
                            class="sub-input-field"
                            style="width: 200px;
                            margin-right: 10px;"
                  ></el-input>
                  <el-button size="mini" type="danger" @click="removeBladeRepairParam(index)" class="delete-btn">删除
                  </el-button>
                </el-form-item>
                <div class="sub-form-actions">
                  <el-button type="primary" size="mini" @click="addBladeRepairParam" class="action-btn">新增参数
                  </el-button>
                  <el-button size="mini" @click="resetBladeRepairParams" class="action-btn">重置</el-button>
                </div>
              </el-form>
            </div>
            <!--工艺参数设置-->
            <div class="sub-form-section mt30">
              <h4 class="sub-section-title">工艺参数设置</h4>
              <el-form :model="form" :rules="processRules" ref="processForm" label-width="150px" class="sub-form">
                <el-form-item
                    v-for="(param, index) in form.processParams"
                    :key="index"
                    :label="param.label"
                    :prop="`processParams[${index}].value`"
                    class="sub-form-item"
                >
                  <el-input v-model="param.value"
                            placeholder="请输入内容"
                            class="sub-input-field"
                            style="width: 200px;
                            margin-right: 10px;"
                  ></el-input>
                  <el-button size="mini" type="danger" @click="removeProcessParam(index)" class="delete-btn">删除
                  </el-button>
                </el-form-item>
                <div class="sub-form-actions">
                  <el-button type="primary" size="mini" @click="addProcessParam" class="action-btn">新增参数</el-button>
                  <el-button size="mini" @click="resetProcessParams" class="action-btn">重置</el-button>
                </div>
              </el-form>
            </div>
          </div>
        </el-col>
      </el-row>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="dialog-btn">取消</el-button>
        <el-button type="primary" @click="submitForm" class="dialog-btn">确认</el-button>
      </span>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog :title="`工单详情 - ${detailForm.id}`" :visible.sync="detailVisible" width="80%">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="form-section">
            <h3 class="section-title">裂纹修复</h3>
            <el-form :model="detailForm" label-width="150px" class="main-form">
              <el-form-item label="叶片裂纹描述">
                <el-input v-model="detailForm.crackDescription"
                          type="textarea"
                          :rows="8" disabled
                          class="input-field"
                ></el-input>
              </el-form-item>
              <!-- 增加间距 -->
              <div style="margin-bottom: 255px;"></div>
              <el-form-item label="上传图片">
                <div v-for="(purl, index) in detailForm.imagePath ? [detailForm.imagePath] : []" :key="index">
                  <!-- 点击图片触发预览 -->
                  <img
                      :src="getImageUrl(purl)"
                      alt="上传图片"
                      style="max-width: 100px; max-height: 100px; cursor: pointer;"
                      @error="handleImageError"
                      @click="showImagePreview(purl)"
                  >
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="form-section">
            <h3 class="section-title">参数设置</h3>
            <div class="sub-form-section">
              <h4 class="sub-section-title">叶片修复参数设置</h4>
              <el-form :model="detailForm" label-width="150px" class="sub-form">
                <el-form-item
                    v-for="(param, index) in detailForm.bladeRepairParams"
                    :key="index"
                    :label="param.label"
                    class="sub-form-item"
                >
                  <el-input v-model="param.value" disabled class="sub-input-field" style="width: 200px;"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="sub-form-section mt30">
              <h4 class="sub-section-title">工艺参数设置</h4>
              <el-form :model="detailForm" label-width="150px" class="sub-form">
                <el-form-item
                    v-for="(param, index) in detailForm.processParams"
                    :key="index"
                    :label="param.label"
                    class="sub-form-item"
                >
                  <el-input v-model="param.value" disabled class="sub-input-field" style="width: 200px;"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false" class="dialog-btn">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog :visible.sync="imagePreviewVisible" :title="`图片预览`" width="80%">
      <img :src="previewImageUrl" style="max-width: 100%; max-height: 80vh; display: block; margin: 0 auto;">
    </el-dialog>
  </div>
</template>

<script>
import {
  listBladeRepairForm,
  getBladeRepairForm,
  addBladeRepairForm,
  updateBladeRepairForm,
  deleteBladeRepairForm
} from '@/api/repair/repairBlade'
import info from '@/views/equipment/info/index.vue'

export default {
  name: 'RepairDataManagement',
  data() {
    return {
      fileList: [],
      queryParams: {
        id: ''
      },
      dateRange: [],
      showSearch: true,
      dataList: [],
      dialogVisible: false,
      isEdit: false,

      form: {
        crackDescription: '',
        imagePath: '',
        createBy: this.getUsername(),
        bladeRepairParams: [
          { label: '叶片裂纹长度', value: '' }
        ],
        processParams: [
          { label: '机器人速度', value: '' },
          { label: '送粉速度', value: '' },
          { label: '激光功率', value: '' },
          { label: '光斑直径', value: '' },
          { label: '离焦量', value: '' }
        ]
      },
      // 定义叶片修复参数校验规则
      bladeRepairRules: {
        bladeRepairParams: [
          {
            type: 'array',
            required: true,
            fields: {
              value: [
                { required: true, message: '该参数不能为空', trigger: 'blur' }
              ]
            },
            message: '叶片修复参数设置不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 定义工艺参数校验规则
      processRules: {
        processParams: [
          {
            type: 'array',
            required: true,
            fields: {
              value: [
                { required: true, message: '该参数不能为空', trigger: 'blur' }
              ]
            },
            message: '工艺参数设置不能为空',
            trigger: 'blur'
          }
        ]
      },
      rules: {
        crackDescription: [
          { required: true, message: '叶片裂纹描述不能为空', trigger: 'blur' }
        ]
      },

      detailVisible: false,
      detailForm: {},
      // 图片预览
      imagePreviewVisible: false,
      previewImageUrl: '',
      selectedRow: null,
      multipleSelection: []
    }
  },
  methods: {
    // 获取当前用户名
    getUsername() {
      // 从本地存储或Vuex获取用户名
      return localStorage.getItem('username') || 'admin'
    },

    // 拼接图片完整路径
    getImageUrl(path) {
      if (!path) return ''
      // 假设图片存储在O:/DICS-picture/picture目录下
      return `file:///O:/DICS-picture/picture/${path}`
    },

    // 查询数据
    async handleQuery() {
      try {
        // const params = {
        //   //查询参数获取工单id
        //   id: this.queryParams.id,
        //   ...(this.dateRange.length > 0 ? {
        //     createdTime: this.dateRange[0],
        //     updatedTime: this.dateRange[1]
        //   } : {})
        // }

      //   listParam(this.queryParams).then((response) => {
      //     this.paramList = response.rows;
      //     this.total = response.total;
      //     this.loading = false;
      //   });
      // },
        const response = await listBladeRepairForm(params)
        console.info('查询工单列表ok', info)
        this.dataList = response.rows;

        // 检查查询结果是否为空
        if (this.dataList.length === 0) {
          this.$message.info('未查询到符合条件的工单，请调整查询条件后重试。')
        }
      } catch (error) {
        console.error('查询工单列表失败', error)
        this.$message.error('查询失败')
      }
    },
    // 重置查询
    resetQuery() {
      this.queryParams = { id: '' }
      this.dateRange = []
      this.handleQuery()
    },
    // 新增
    handleAdd() {
      this.isEdit = false
      this.form = {
        crackDescription: '',
        imagePath: '',
        createBy: this.getUsername(),
        bladeRepairParams: [
          { label: '叶片裂纹长度', value: '' }
        ],
        processParams: [
          { label: '机器人速度', value: '' },
          { label: '送粉速度', value: '' },
          { label: '激光功率', value: '' },
          { label: '光斑直径', value: '' },
          { label: '离焦量', value: '' }
        ]
      }
      this.fileList = []
      this.dialogVisible = true
    },
    // 修改选中项
    async handleEditSelected() {
      if (this.selectedRow) {
        try {
          const response = await getBladeRepairForm(this.selectedRow.id)
          this.isEdit = true
          this.form = { ...response }

          // 处理图片
          if (response.imagePath) {
            this.fileList = [{ url: this.getImageUrl(response.imagePath), name: 'image' }]
          } else {
            this.fileList = []
          }

          this.dialogVisible = true
        } catch (error) {
          console.error('获取工单详情失败', error)
          this.$message.error('获取详情失败')
        }
      }
    },
    // 修改
    async handleEdit(row) {
      try {
        const response = await getBladeRepairForm(row.id)
        this.isEdit = true
        this.form = { ...response }

        // 处理图片
        if (response.imagePath) {
          this.fileList = [{ url: this.getImageUrl(response.imagePath), name: 'image' }]
        } else {
          this.fileList = []
        }

        this.dialogVisible = true
      } catch (error) {
        console.error('获取工单详情失败', error)
        this.$message.error('获取详情失败')
      }
    },
    // 删除选中项
    async handleDeleteSelected() {
      if (this.selectedRow) {
        this.$confirm('是否确认删除该数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          try {
            await deleteBladeRepairForm([this.selectedRow.id])
            this.dataList = this.dataList.filter(item => item.id !== this.selectedRow.id)
            this.$message.success('删除成功')
            this.selectedRow = null
            this.multipleSelection = []
          } catch (error) {
            console.error('删除工单失败', error)
            this.$message.error('删除失败')
          }
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      }
    },
    // 删除
    async handleDelete(row) {
      this.$confirm('是否确认删除该数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteBladeRepairForm([row.id])
          this.dataList = this.dataList.filter(item => item.id !== row.id)
          this.$message.success('删除成功')
        } catch (error) {
          console.error('删除工单失败', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 提交表单
    async submitForm() {
      // 先校验表单
      this.$refs.form.validate((formValid) => {
        if (!formValid) return false

        // 校验叶片修复参数
        this.$refs.bladeRepairForm.validate((bladeRepairValid) => {
          if (!bladeRepairValid) {
            this.$message.error('请填写完整裂纹修复参数信息')
            return false
          }

          // 校验工艺参数
          this.$refs.processForm.validate(async(processValid) => {
            if (processValid) {
              try {
                let response
                const formData = new FormData()

                // 序列化表单数据
                formData.append('form', JSON.stringify({
                  ...this.form,
                  // 移除fileList等非持久化字段
                  crackDescription: this.form.crackDescription,
                  imagePath: this.fileList.length > 0 ? this.fileList[0].name : this.form.imagePath,
                  createBy: this.form.createBy,
                  bladeRepairParams: this.form.bladeRepairParams,
                  processParams: this.form.processParams
                }))

                // 添加图片
                if (this.fileList.length > 0) {
                  formData.append('image', this.fileList[0].raw)
                }

                if (this.isEdit) {
                  // 修改工单
                  response = await updateBladeRepairForm(formData)
                  this.$message.success('修改成功')
                } else {
                  // 新增工单
                  response = await addBladeRepairForm(formData)
                  this.$message.success('新增成功')

                  // 刷新列表
                  this.handleQuery()
                }

                this.dialogVisible = false
              } catch (error) {
                console.error('提交表单失败', error)
                this.$message.error('操作失败')
              }
            } else {
              this.$message.error('请填写完整工艺参数信息')
              return false
            }
          })
        })
      })
    },
    // 新增叶片修复参数
    addBladeRepairParam() {
      this.$prompt('请输入新参数名称', '新增参数', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value) {
          this.form.bladeRepairParams.push({ label: value, value: '' })
        }
      }).catch(() => {
        // 用户取消操作
      })
    },
    // 删除叶片修复参数
    removeBladeRepairParam(index) {
      this.form.bladeRepairParams.splice(index, 1)
    },

    // 重置叶片修复参数
    resetBladeRepairParams() {
      this.form.bladeRepairParams = [
        { label: '叶片裂纹长度', value: '' }
      ]
    },
    // 详情
    async handleDetail(row) {
      try {
        const response = await getBladeRepairForm(row.id)
        this.detailForm = { ...response }
        this.detailVisible = true
      } catch (error) {
        console.error('获取工单详情失败', error)
        this.$message.error('获取详情失败')
      }
    },
    // 图片预览
    showImagePreview(url) {
      this.previewImageUrl = url
      this.imagePreviewVisible = true
    },
    // 处理表格选中变化
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.selectedRow = selection.length > 0 ? selection[0] : null
    },
    // 处理图片加载失败
    handleImageError(e) {
      e.target.src = 'https://via.placeholder.com/100'
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.form.imagePath = ''
      this.fileList = fileList
    },
    // 预览图片
    handlePreview(file) {
      this.previewImageUrl = file.url
      this.imagePreviewVisible = true
    },
    // 上传图片
    beforeUpload(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.fileList.push({
          name: file.name,
          url: e.target.result,
          raw: file
        })
        this.form.imagePath = file.name
      }
      reader.readAsDataURL(file)
    },
    // 新增工艺参数
    addProcessParam() {
      this.$prompt('请输入新参数名称', '新增参数', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value) {
          this.form.processParams.push({ label: value, value: '' })
        }
      }).catch(() => {
        // 用户取消操作
      })
    },
    // 删除工艺参数
    removeProcessParam(index) {
      this.form.processParams.splice(index, 1)
    },
    // 重置工艺参数
    resetProcessParams() {
      this.form.processParams = [
        { label: '机器人速度', value: '' },
        { label: '送粉速度', value: '' },
        { label: '激光功率', value: '' },
        { label: '光斑直径', value: '' },
        { label: '离焦量', value: '' }
      ]
    }
  },
  mounted() {
    this.handleQuery()
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.mt10 {
  margin-top: 10px;
}

.ml10 {
  margin-left: 10px;
}

.mt20 {
  margin-top: 20px;
}

.mt30 {
  margin-top: 30px;
}

.form-section {
  border: 1px solid #ebeef5;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.section-title {
  margin-top: 0;
  margin-bottom: 25px;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.sub-form-section {
  margin-top: 25px;
  padding: 20px;
  border: 1px solid #f0f2f5;
  border-radius: 6px;
  background-color: #f9fafc;
}

.sub-section-title {
  margin-top: 0;
  margin-bottom: 15px;
  color: #606266;
  font-size: 16px;
  font-weight: 500;
}

.main-form {
  padding: 10px;
}

.sub-form {
  padding: 10px;
}

.input-field, .sub-input-field {
  border-radius: 4px;
  transition: border-color 0.3s;
}

.input-field:focus, .sub-input-field:focus {
  border-color: #409EFF;
}

.delete-btn {
  background-color: #f56c6c;
  color: white;
  transition: background-color 0.3s;
}

.delete-btn:hover {
  background-color: #dd6161;
}

.action-btn {
  margin-right: 10px;
}

.upload-btn {
  border-radius: 4px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.dialog-btn {
  border-radius: 4px;
  padding: 8px 20px;
}

.main-form-item, .sub-form-item {
  margin-bottom: 15px;
}

.sub-form-actions, .main-form-actions {
  margin-top: 15px;
}
</style>
